package com.test.netty.niotest;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class NioTestMain {

    public static void main(String[] args) {
        String s = NioTestMain.nioReadFile("D:\\Data\\Desktop\\important.txt");
        NioTestMain.nioWriteFile(s, "D:\\Data\\Desktop\\important11.txt");
    }

    public static String nioReadFile(String filePath) {
        FileInputStream fis = null;
        StringBuilder sb = new StringBuilder();
        String s = "";
        try {
            fis = new FileInputStream(filePath);
            FileChannel fc = fis.getChannel();
            ByteBuffer buff = ByteBuffer.allocate(1024);
            fc.read(buff);
            buff.flip();
            byte[] bytes = buff.array();
            s = new String(bytes, Charset.forName("gb2312"));
            System.out.println(s);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return s;
    }

    public static void nioWriteFile(String content, String filePath) {
        FileOutputStream fos = null;
        try {
            File f = new File(filePath);
            if (!f.exists()) {
                f.createNewFile();
            }
            fos = new FileOutputStream(filePath, true);
            FileChannel fc = fos.getChannel();
            ByteBuffer buff = ByteBuffer.allocate( 2048 );
            buff.put(content.getBytes(Charset.forName("utf-8")));
            buff.flip();
            fc.write(buff);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
